go to previous page   go to home page   go to next page

Does DataInputStream.close() throw an exception?

Answer:

Yes, it throws an IOException when it encounters a problem.


Exception thrown by a catch{} Block

// Loop with problems
public static void main()
{
  . . .
   
  try
  {
    while ( true )
      sum += instr.readInt();
  }
  
  catch ( EOFException eof )
  {
    System.out.println( "The sum is: " + sum );
    instr.close(); <—— throws IOException 
  }
  
  catch ( IOException eof ) <—— this  catch is for the try{} block 
  {                              not for the previous catch{} block
  
    System.out.println( "Problem reading input" );
    instr.close(); <—— throws IOException 
  }
  
  . . .
  
}

So there is a problem. The close() method inside the catch{} block throws an IOException which is not caught.

There are various ways to deal with this. One possibility is not to catch the exception that close() throws. Then the header must be

public static void main(String[] args) throws IOException

QUESTION 11:

Can a try{}/catch{} be nested inside an outer try{} block?